package com.qinggeng.project.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinggeng.common.enums.JobUserTypeEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.config.thread.ThreadPoolExecutorUtil;
import com.qinggeng.project.api.dto.JobDliveryDTO;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.system.domain.*;
import com.qinggeng.project.system.mapper.JobDliveryMapper;
import com.qinggeng.project.system.mapper.JobMessageMapper;
import com.qinggeng.project.system.service.*;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.testng.annotations.IFactoryAnnotation;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class JobDliveryServiceImpl  implements JobDliveryService {

    @Resource
    private JobDliveryMapper jobDliveryMapper;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private IJobUserService jobUserService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ResumeServiceImpl  resumeService;

    @Autowired
    private JobMessageService jobMessageService;


    //求职
    @Override
    public boolean insertJobUserDlivery(JobDlivery jobDlivery) {
        if (null ==jobDlivery){
            throw  new CustomException("jobDlivery is null ");
        }
        Long resumeUserId=jobUserService.getJobUserId();
        jobDlivery.setResumeUserId(resumeUserId);
        jobDlivery.setType(Integer.valueOf(JobUserTypeEnum.RESUME_USER.getType()));
        boolean bl=getDliveryByResumeUserIdAndPositionId(jobDlivery);
        if (bl){
            return   true;
        }
        return insertDlivery(jobDlivery);
    }

    //公司邀请
    @Override
    public boolean insertCompanyDlivery(JobDliveryDTO jobDlivery) {
        if (null ==jobDlivery){
            throw  new CustomException("jobDlivery is null ");
        }
        Long resumeId=jobDlivery.getResumeId();
        Resume resume=resumeService.getResumeById(resumeId);
        if (null==resume){
            throw  new CustomException("resume is null ");
        }
        Long resumeUserId=resume.getJobUserId();
        if (resumeUserId==null){
            throw  new CustomException("resumeUserId is null ");
        }
        jobDlivery.setResumeUserId(resumeUserId);
        jobDlivery.setType(Integer.valueOf(JobUserTypeEnum.POSITION_USER.getType()));
        boolean bl=getDliveryByResumeUserIdAndPositionId(jobDlivery);
        if (bl){
            return  true;
        }
        return insertDlivery(jobDlivery);
    }

    private  boolean  insertDlivery(JobDlivery jobDlivery){
        Long positionId=jobDlivery.getPositionId();
        if (positionId ==null){
            throw  new CustomException(" PositionId is null ");
        }

        Position position=positionService.getPositionById(positionId);
        if (position==null){
            throw  new CustomException(" position is null ");
        }
        Long resumeUserId=jobDlivery.getResumeUserId();
        if (null ==resumeUserId){
            throw  new CustomException(" resumeUserId is null ");
        }

        Long companyId=position.getCompanyId();
        if (companyId==null){
            throw  new CustomException(" companyId is null ");
        }
        Company company=companyService.getCompanyById(companyId);
        String companyName="";
        if (company !=null){
            companyName=company.getName();
            jobDlivery.setCompanyName(companyName);
        }

        String positionName= position.getName();
        if (StringUtils.isNotEmpty(positionName)){
            jobDlivery.setPositionName(positionName);
        }
        Date date =new Date();
        jobDlivery.setDeliveryDate(date);
        jobDlivery.setCreateTime(date);
        jobDlivery.setUpdateTime(date);
        Long userId=ApiUtils.getUserId();
        Resume resume=resumeService.getResumeByUserId(userId);
        if (resume !=null){
            jobDlivery.setResume(resume);

        }
        jobDlivery.setPosition(position);
        jobDlivery.setCompanyId(companyId);
        Long positionUserId=position.getJobUserId();
        jobDlivery.setPositionUserId(positionUserId);
        jobDlivery.setIsRead(0);
        jobDlivery.setStatus(0);
        jobDlivery.setDelFlag(0);
        boolean bl=jobDliveryMapper.insertSelective(jobDlivery)>0;


        //如果是职位类型发送给用户
        if (String.valueOf(jobDlivery.getType()).equals(JobUserTypeEnum.POSITION_USER.getType())){
            JobUser jobUser=jobUserService.getJobUserById(positionUserId);
            if (jobUser!=null) {
                JobMessage jobMessage = new JobMessage();
                jobMessage.setResumeUserId(resumeUserId);
                jobMessage.setPositionUserId(positionUserId);
                jobMessage.setJobDelivernId(jobDlivery.getId());
                jobMessage.setType(Integer.valueOf(JobUserTypeEnum.RESUME_USER.getType()));
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("companyId", companyId);
                jsonObject.put("companyName", companyName);
                jsonObject.put("positionId", positionId);
                jsonObject.put("positionName", positionName);
                jsonObject.put("salary", position.getSalary());
                jsonObject.put("phone",jobUser.getPhone());
                jsonObject.put("avatar",jobUser.getAvatar());
                jobMessage.setContent(jsonObject.toJSONString());
                sendMessgae(jobMessage);
            }

        }

        //如果是简历类型发送给公司
        if (String.valueOf(jobDlivery.getType()).equals(JobUserTypeEnum.RESUME_USER.getType())){
            JobUser jobUser=jobUserService.getJobUserById(resumeUserId);
            if (jobUser!=null){
                JobMessage jobMessage =new JobMessage();
                jobMessage.setResumeUserId(resumeUserId);
                jobMessage.setPositionUserId(positionUserId);
                jobMessage.setJobDelivernId(jobDlivery.getId());
                jobMessage.setType(Integer.valueOf(JobUserTypeEnum.POSITION_USER.getType()));
                String userName=jobUser.getUserName();
                JSONObject jsonObject =new JSONObject();
                jsonObject.put("userName",userName);
                jsonObject.put("positionId",positionId);
                jsonObject.put("avatar",jobUser.getAvatar());
                jsonObject.put("companyName",companyName);
                jsonObject.put("companyId",companyId);
                jsonObject.put("positionName",positionName);
                jsonObject.put("salary",position.getSalary());
                if (resume !=null){
                    jsonObject.put("resumeId",resume.getId());
                }
                jsonObject.put("phone",jobUser.getPhone());
                jobMessage.setContent(jsonObject.toJSONString());
                sendMessgae(jobMessage);
            }
        }
        return bl;
    }

    private  void sendMessgae(JobMessage jobMessage){
        ThreadPoolExecutor executor=ThreadPoolExecutorUtil.getPoll();
        executor.execute(new Runnable() {
            @Override
            public void run() {

                jobMessageService.sendMessageJobUser(jobMessage);
            }
        });
    }
    @Override
    public List<JobDlivery> listJobDliveryByResumeUserId() {
        Long jobUserId=jobUserService.getJobUserId();
        Example example =new Example(JobDlivery.class);
        example.createCriteria().andEqualTo("resumeUserId",jobUserId);
        example.createCriteria().andEqualTo("type",JobUserTypeEnum.RESUME_USER.getType());
        return jobDliveryMapper.selectByExample(example);
    }


    @Override
    public List<JobDlivery> listJobDliveryByPositionUserId() {
        Long jobUserId=jobUserService.getJobUserId();
        Example example =new Example(JobDlivery.class);
        example.createCriteria().andEqualTo("positionUserId",jobUserId);
        example.createCriteria().andEqualTo("type",JobUserTypeEnum.POSITION_USER.getType());
        return jobDliveryMapper.selectByExample(example);
    }

    @Override
    public JobDlivery getJobDliveryById(JobDlivery jobDlivery) {
        Long id=jobDlivery.getId();
        if (null ==id){
            throw  new CustomException("id is null");
        }
        return jobDliveryMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer getJobDeliveryCountByPositionUserId() {

        List<JobDlivery> jobDeliveryList= this.listJobDliveryByPositionUserId();
        if(CollectionUtils.isEmpty(jobDeliveryList)){
            return 0;
        }
        return jobDeliveryList.size();
    }


    @Override
    public Integer getJobDeliveryCountByResumeUserId() {
        List<JobDlivery> jobDeliveryList= this.listJobDliveryByResumeUserId();
        if(CollectionUtils.isEmpty(jobDeliveryList)){
            return 0;
        }
        return jobDeliveryList.size();
    }


    //该用户是否投递过简历 投递过 true  没有投递过 false
    public   JobDlivery getDlivery(JobDlivery jobDlivery){
        if (null == jobDlivery){
            throw  new CustomException("jobDlivery is null");
        }
        Long resumeUserId=jobDlivery.getResumeUserId();

        if (null == resumeUserId){
            throw  new CustomException("resumeUserId is null");
        }
        Long positionId=jobDlivery.getPositionId();
        if (null == positionId){

            throw  new CustomException("positionId is null");
        }
        Example example =new Example(JobDlivery.class);
        example.setOrderByClause("id  limit 1");
        example.createCriteria().andEqualTo("resumeUserId",resumeUserId)
                .andEqualTo("positionId",positionId)
                .andEqualTo("type",jobDlivery.getType());
        JobDlivery dlivery=jobDliveryMapper.selectOneByExample(example);
        return  dlivery;
    }

    //该用户是否投递过简历 投递过 true  没有投递过 false
    public   boolean getDliveryByResumeUserIdAndPositionId(JobDlivery jobDlivery){

        return getDlivery(jobDlivery) !=null;
    }

    @Override
    public   JobDlivery getDeliveryByResumeUserIdAndPositionIdAndType(JobDlivery jobDlivery){
        if (null == jobDlivery){
            throw  new CustomException("jobDelivery is null");
        }
        Long resumeUserId=jobDlivery.getResumeUserId();

        if (null == resumeUserId){
            throw  new CustomException("resumeUserId is null");
        }
        Long positionId=jobDlivery.getPositionId();
        if (null == positionId){
            throw  new CustomException("positionId is null");
        }
        Integer type=jobDlivery.getType();
        if(null==type){
            throw  new CustomException("type is null");
        }
        Example example =new Example(JobDlivery.class);
        example.setOrderByClause("id desc limit 1");
        example.createCriteria().andEqualTo("resumeUserId",resumeUserId)
                .andEqualTo("positionId",positionId)
                .andEqualTo("type",type);
        JobDlivery job=jobDliveryMapper.selectOneByExample(example);
        return  job;
    }


    @Override
    public   JobDlivery getDeliveryByResumeUserIdAndPositionUserIdAndType(JobDlivery jobDlivery){
        if (null == jobDlivery){
            throw  new CustomException("jobDelivery is null");
        }
        Long resumeUserId=jobDlivery.getResumeUserId();
        if (null == resumeUserId){
            throw  new CustomException("resumeUserId is null");
        }
        Long positionUserId=jobDlivery.getPositionUserId();
        if (null == positionUserId){
            throw  new CustomException("positionUserId is null");
        }
        Integer type=jobDlivery.getType();
        if(null==type){
            throw  new CustomException("type is null");
        }
        Example example =new Example(JobDlivery.class);
        example.setOrderByClause("id desc limit 1");
        example.createCriteria().andEqualTo("resumeUserId",resumeUserId)
                .andEqualTo("positionUserId",positionUserId)
                .andEqualTo("type",type);
        return jobDliveryMapper.selectOneByExample(example) ;
    }

    @Override
    public boolean checkPositionIsDelivery(Long resumeUserId,Long positionId){
        JobDlivery jobDlivery=new JobDlivery();
        jobDlivery.setResumeUserId(resumeUserId);
        jobDlivery.setPositionId(positionId);
        jobDlivery.setType(Integer.parseInt(JobUserTypeEnum.RESUME_USER.getType()));
        return this.getDeliveryByResumeUserIdAndPositionIdAndType(jobDlivery)!=null;
    }

    @Override
    public boolean checkResumeIsInterested(Long positionUserId,Long resumeUserId){
        JobDlivery jobDlivery=new JobDlivery();
        jobDlivery.setResumeUserId(resumeUserId);
        jobDlivery.setPositionUserId(positionUserId);
        jobDlivery.setType(Integer.parseInt(JobUserTypeEnum.POSITION_USER.getType()));
        return this.getDeliveryByResumeUserIdAndPositionUserIdAndType(jobDlivery)!=null;
    }


}
